// pages/person/addressAdd/addressAdd.js
import Notify from '../../../miniprogram_npm/@vant/weapp/notify/notify'
import { queryProince } from '../../../api/personApply.js'
import { addAddress } from '../../../api/address.js'
import WxValidate from '../../../utils/WxValidate.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    provinceCityAreaShow: false,
    provinceCityArea: [],
    cityMap: {},
    areaMap: {},
    overlayShow: false,
    form: {
      username: '',
      mobile: '',
      provinceCityArea: '',
      province: '',
      provinceVal: '',
      city: '',
      cityVal: '',
      area: '',
      areaVal: '',
      address: ''
    }
  },

  /**
   * 初始化规则验证
   */
  initValidate() {
    const rules = {
      username: {
        required: true,
        minlength:2
      },
      mobile: {
        required: true,
        tel: true
      },
      provinceCityArea: {
        required: true
      },
      address: {
        required: true
      }
    }
    const messages = {
      username: {
        required: '您的姓名必填',
        minlength:'请输入正确的姓名'
      },
      mobile: {
        required: '您的手机号必填',
        tel:'请输入正确的手机号'
      },
      provinceCityArea: {
        required: '收件人所在区域必选'
      },
      address: {
        required: '收件人详细地址必填'
      }
    }
    this.WxValidate = new WxValidate(rules, messages)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initValidate()//验证规则函数

    //读取 省市区
    queryProince().then(res => {
      const provinceList = res.provinceList
      const areaMap = res.areaMap
      const cityMap = res.cityMap
      const initCityList = cityMap[provinceList[0].id];
      this.setData({
        cityMap: cityMap,
        areaMap: areaMap,
        provinceCityArea: [
          {
            values: provinceList,
            className: 'column1'
          },
          {
            values: cityMap[provinceList[0].id],
            className: 'column2',
            defaultIndex: 0
          },
          {
            values: areaMap[initCityList[0].id],
            className: 'column3',
            defaultIndex: 0
          }
        ]
      })
    }).catch(err=>{
      Notify({ type: 'danger', message: "请求异常，请联系管理员" })
    });
  },
  /**
   * 监听文本框输入
   */
  onChangeFile(event) {
    // event.detail 为当前输入的值
    if(event.currentTarget.id == 'username'){
      const form = this.data.form;
      form.username = event.detail
      this.setData({
        form: form
      })
    }
    if(event.currentTarget.id == 'mobile'){
      const form = this.data.form;
      form.mobile = event.detail
      this.setData({
        form: form
      })
    }
    if(event.currentTarget.id == 'address'){
      const form = this.data.form;
      form.address = event.detail
      this.setData({
        form: form
      })
    }
  },
  /**
   * 省市区 级联 
   */
  onChange(event) {
    const { picker, value, index } = event.detail;
    if(index == 0){
      var cityList = this.data.cityMap[value[0].id]
      picker.setColumnValues(1, cityList);
      picker.setColumnValues(2, this.data.areaMap[cityList[0].id]);
    }
    if(index == 1){
      var areaList = this.data.areaMap[value[1].id]
      picker.setColumnValues(2, areaList);
    }
  },
  provinceCityAreaPickShow: function() {
    this.setData({
      provinceCityAreaShow: true
    })
  },
  onConfirm(event) {
    const { picker, value, index } = event.detail;
    const form = this.data.form
    form.provinceCityArea = value[0].name + " " + value[1].name + " " + value[2].name
    form.province = value[0].id
    form.provinceVal = value[0].name
    form.city = value[1].id
    form.cityVal = value[1].name
    form.area = value[2].id
    form.areaVal = value[2].name
    
    this.setData({
      provinceCityAreaShow: false,
      form: form
    })
  },
  onCancel() {
    this.setData({
      provinceCityAreaShow: false
    })
  },
  /**
   * 表单提交
   */
  formSubmit: function(e) {
    
    const params = e.detail.value
    //校验表单
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      Notify({ type: 'danger', message: error.msg })
      return false
    }

    this.setData({
      overlayShow: true
    })

    const dataParams = {
      'username': this.data.form.username,
      'mobile': this.data.form.mobile,
      'province': this.data.form.province,
      'provinceVal': this.data.form.provinceVal,
      'city': this.data.form.city,
      'cityVal': this.data.form.cityVal,
      'area': this.data.form.area,
      'areaVal': this.data.form.areaVal,
      'address': this.data.form.address
    }

    addAddress(dataParams).then(res => {
      this.setData({
        overlayShow: false
      })
      Notify({ type: 'success', message: "新增成功" })
      var pages = getCurrentPages(); // 当前页面
      var beforePage = pages[pages.length - 2]; // 前一个页面
      wx.navigateBack({
        success: function() {
            beforePage.loadAddrssList(); // 执行前一个页面的onLoad方法
        }
      });
    }).catch(err=>{
      this.setData({
        overlayShow: false
      })
      Notify({ type: 'danger', message: err })
    });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})